﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using MVCSoict.Models;
using Newtonsoft.Json;

namespace MVCSoict.Controllers
{
    public class UserController : Controller
    {
        private staffsoictEntities1 db = new staffsoictEntities1();
        private JsonSerializerSettings jsonSettings = new JsonSerializerSettings()
        {
            PreserveReferencesHandling = PreserveReferencesHandling.Objects
        };
        // GET: /User/
        public ActionResult Index()
        {
            return View(db.Users.ToList());
        }

        public string Login(string username, string password)
        {
            string res = string.Empty;
            try
            {
                using (var context = new staffsoictEntities1())
                {
                    //context.Configuration.ProxyCreationEnabled = false;                    
                    var users = from u in context.Users
                                where u.username.Equals(username) && u.password.Equals(password)
                                select u;
                    if (users.ToList().Count > 0)
                    {
                        User user = users.ToList()[0];
                        user.username = user.username.Trim();
                        user.phone = user.phone.Trim();
                        user.name = user.name.Trim();
                        user.fax = user.fax.Trim();
                        user.email = user.email.Trim();
                        user.password = string.Empty;
                        user.room = user.room.Trim();
                        res = JsonConvert.SerializeObject(user, jsonSettings);
                        Session.Add("username", users.ToList()[0].username);
                    }
                }
            }
            catch (Exception ex)
            {
                res = ex.Message;
            }
            return res;
        }

        public string Select(string keyword, int page, int pagesize)
        {
            string jsonResult = string.Empty;

            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "user_select"))
                {
                    try
                    {
                        using (var context = new staffsoictEntities1())
                        {
                            var users = from u in context.Users
                                        where u.username.Contains(keyword) || u.details.Contains(keyword) || u.email.Contains(keyword)
                                        || u.name.Contains(keyword) || u.student.Contains(keyword)
                                        orderby u.username
                                        select u;

                            var pageData = users.Skip((page - 1) * pagesize).Take(pagesize).ToList();
                            foreach (var user in pageData)
                            {
                                jsonResult += JsonConvert.SerializeObject(user, jsonSettings);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        jsonResult = ex.Message;
                    }
                }                
            }            
            return jsonResult;
        }

        public void Logout()
        {
            if (Session["user"] != null)
            {
                Session.RemoveAll();
            }
        }

        /// <summary>
        /// thêm người dùng
        /// </summary>
        /// <param name="user"></param>
        /// <returns>trả về user vừa thêm</returns>
        public string Add([Bind(Include = "username,password,name,room,email,phone,fax,avartar,student,state,details")] User user)
        {
            string res = string.Empty;
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "user_add"))
                {
                    try
                    {
                        db.Users.Add(user);
                        db.SaveChanges();
                        res = JsonConvert.SerializeObject(user, jsonSettings);
                    }
                    catch (Exception ex)
                    {
                        res = ex.Message;
                    }
                }
            }
            return res;
        }

        public string Xoa(string username)
        {
            string res = string.Empty;
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "user_xoa"))
                {
                    User user = db.Users.Find(username);
                    ICollection<Brief> listBrief = user.Briefs;
                    ICollection<Lesson> listLesson = user.Lessons;
                    for (int i = 0; i < listBrief.Count; i++)
                    {
                        db.Briefs.Remove(listBrief.ElementAt(i));
                        db.SaveChanges();
                    }
                    for (int j = 0; j < listLesson.Count; j++)
                    {
                        db.Lessons.Remove(listLesson.ElementAt(j));
                        db.SaveChanges();
                    }
                    try
                    {
                        db.Users.Remove(user);
                        db.SaveChanges();
                        res = JsonConvert.SerializeObject(user, jsonSettings);
                    }
                    catch (Exception ex)
                    {
                        res = ex.Message;
                    }
                }
            }
            return res;
        }

        //tested
        public string Update([Bind(Include = "username,password,name,room,email,phone,fax,avartar,student,state,details")] User user)
        {
            string res = string.Empty;
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "user_update"))
                {
                    try
                    {
                        db.Entry(user).State = EntityState.Modified;
                        db.SaveChanges();
                        res = JsonConvert.SerializeObject(user, jsonSettings);
                    }
                    catch (Exception ex)
                    {
                        res = ex.Message;
                    }
                }
            }
            return res;
        }

        public string Get(string id)
        {
            string res = string.Empty;
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "user_get"))
                {
                    try
                    {
                        var users = from u in db.Users
                                    where u.username.Equals(id)
                                    select u;
                        if ((users.ToList<User>().Count() > 0))
                            res = JsonConvert.SerializeObject(users.ToList<User>()[0], jsonSettings);
                    }
                    catch (Exception ex)
                    {
                        res = ex.Message;
                    }
                }
            }
            return res;
        }

        public string AddRole(string roleId, string username)
        {
            string res = string.Empty;
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "user_addrole"))
                {
                    try
                    {
                        Role role = db.Roles.Find(roleId);
                        User user = db.Users.Find(username);
                        user.Roles.Add(role);
                        db.Entry(user).State = EntityState.Modified;
                        db.SaveChanges();
                        res = JsonConvert.SerializeObject(role, jsonSettings);
                    }
                    catch (Exception ex)
                    {
                        res = ex.Message;
                    }
                }
            }
            return res;
        }

        public string RemoveRole(string rid, string username)
        {
            string res = string.Empty;
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "user_removerole"))
                {
                    try
                    {
                        Role role = db.Roles.Find(rid);
                        User user = db.Users.Find(username);
                        user.Roles.Remove(role);
                        db.Entry(user).State = EntityState.Modified;
                        db.SaveChanges();
                        res = JsonConvert.SerializeObject(1, jsonSettings);
                    }
                    catch (Exception ex)
                    {

                    }
                }
            }
            return res;
        }

        public string AddProject(string pid, string username)
        {
            string res = string.Empty;
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "user_addproject"))
                {
                    try
                    {
                        Project project = db.Projects.Find(pid);
                        User user = db.Users.Find(username);
                        user.Projects.Add(project);
                        db.Entry(user).State = EntityState.Modified;
                        db.SaveChanges();
                        res = JsonConvert.SerializeObject(project, jsonSettings);
                    }
                    catch (Exception ex)
                    {
                        res = ex.Message;
                    }
                }
            }
            return res;
        }

        public string RemoveProject(string pid, string username)
        {
            string res = string.Empty;
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "user_removeproject"))
                {
                    try
                    {
                        Project project = db.Projects.Find(pid);
                        User user = db.Users.Find(username);
                        user.Projects.Remove(project);
                        db.Entry(user).State = EntityState.Modified;
                        db.SaveChanges();
                        res = JsonConvert.SerializeObject(1, jsonSettings);
                    }
                    catch (Exception ex)
                    {

                    }
                }
            }
            return res;
        }

        public string AddTitle(int tid, string username)
        {
            string res = string.Empty;
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "user_addtitle"))
                {
                    try
                    {
                        Title title = db.Titles.Find(tid);
                        User user = db.Users.Find(username);
                        user.Titles.Add(title);
                        db.Entry(user).State = EntityState.Modified;
                        db.SaveChanges();
                        res = JsonConvert.SerializeObject(title, jsonSettings);
                    }
                    catch (Exception ex)
                    {
                        res = ex.Message;
                    }
                }
            }
            return res;
        }

        public string RemoveTitle(int tid, string username)
        {
            string res = string.Empty;
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "user_removetitle"))
                {
                    try
                    {
                        Title title = db.Titles.Find(tid);
                        User user = db.Users.Find(username);
                        user.Titles.Remove(title);
                        db.Entry(user).State = EntityState.Modified;
                        db.SaveChanges();
                        res = JsonConvert.SerializeObject(1, jsonSettings);
                    }
                    catch (Exception ex)
                    {

                    }
                }
            }
            return res;
        }

        public string SelectLesson(string username, string fromdate, string todate)
        {
            string jsonResult = string.Empty;
            DateTime fromDate = DateTime.Parse(fromdate);
            DateTime toDate = DateTime.Parse(todate);
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "lesson_selectdate"))
                {
                    using (var context = new staffsoictEntities1())
                    {
                        var lessions = from l in context.Lessons
                                       where (l.starttime > fromDate) && (l.endtime < toDate)
                                       orderby l.lid
                                       select l;

                        foreach (var less in lessions.ToList())
                        {
                            jsonResult += JsonConvert.SerializeObject(less, jsonSettings);
                        }
                    }
                }
            }
            return jsonResult;
        }

        // GET: /User/Details/5
        public ActionResult Details(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            User user = db.Users.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        // GET: /User/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: /User/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "username,password,name,room,email,phone,fax,avartar,student,state,details")] User user)
        {
            if (ModelState.IsValid)
            {
                db.Users.Add(user);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(user);
        }

        // GET: /User/Edit/5
        public ActionResult Edit(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            User user = db.Users.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        // POST: /User/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "username,password,name,room,email,phone,fax,avartar,student,state,details")] User user)
        {
            if (ModelState.IsValid)
            {
                db.Entry(user).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(user);
        }

        // GET: /User/Delete/5
        public ActionResult Delete(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            User user = db.Users.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        // POST: /User/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(string id)
        {
            User user = db.Users.Find(id);
            db.Users.Remove(user);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
